package com.cskaoyan.demo9.servlet;

import com.cskaoyan.demo9.bean.PageData;
import com.cskaoyan.demo9.bean.PageParameter;
import com.cskaoyan.demo9.bean.vo.BaseRespVo;
import com.cskaoyan.demo9.common.CommonServlet;
import com.cskaoyan.demo9.mapper.MarketGoodsMapper;
import com.cskaoyan.demo9.model.MarketGoods;
import com.cskaoyan.demo9.model.MarketGoodsExample;
import com.cskaoyan.demo9.util.JacksonUtil;
import com.cskaoyan.demo9.util.MyBatisUtil;
import com.github.pagehelper.PageHelper;
import lombok.SneakyThrows;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/admin/goods/*")
public class AdminGoodsServlet extends CommonServlet {
    @SneakyThrows
    public void list(HttpServletRequest request, HttpServletResponse response) {
        //设置响应报文的编码方式
        response.setContentType("application/json;charset=utf-8");
        //将请求报文的参数封装成对象、方便使用
        PageParameter pageParameter = PageParameter.init(request.getParameterMap());

        //根据请求报文去数据库进行查询
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        MarketGoodsMapper goodsMapper = sqlSession.getMapper(MarketGoodsMapper.class);
        //开启分页、传入page和limit  要在执行查询前开启分页
        PageHelper.startPage(pageParameter.getPage(),pageParameter.getLimit());
        //用example进行简化
        //排序用的两个参数
        MarketGoodsExample example = new MarketGoodsExample();
        example.setOrderByClause(pageParameter.getSort()+" "+pageParameter.getOrder());
        MarketGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andGoodsSnEqualTo("1006013");
        criteria.andNameLike("%羊毛%");
        criteria.andCategoryIdEqualTo(1008009);

        //调用方法进行查询
        List<MarketGoods> goodsList = goodsMapper.selectByExample(example);
        //封装查询结果
        PageData data = PageData.list(goodsList);
        sqlSession.close();
        //分装响应报文的其他部分
        BaseRespVo baseRespVo = BaseRespVo.ok(data);
        String jsonStr = JacksonUtil.write(baseRespVo);
        //写入响应报文
        response.getWriter().println(jsonStr);
    }
}
